package com.peng.community.service.impl;

import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.User;
import com.peng.community.mapper.UserMapper;
import com.peng.community.service.UserService;
import com.peng.community.util.CommunityUtils;
import com.peng.community.util.MailClient;
import com.peng.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService, CommunityConstant {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findUserById(int id) {
        User user = getCache(id);
        if (user != null) {
            return user;
        }
        return initCache(id);
    }

    @Autowired
    MailClient mailClient;

    @Autowired
    TemplateEngine templateEngine;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public Map<String, Object> register(User user) {

        if (user == null) {
            throw new IllegalArgumentException("用户不能为空");
        }

        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameError","用户名不能为空");
            return map;
        }

        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordError","密码不能为空");
            return map;
        }

        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailError","邮箱不能为空");
            return map;
        }

        User u = userMapper.selectByName(user.getUsername());

        if (u != null) {
            map.put("usernameError","用户名已经存在");
            return map;
        }

        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailError","邮箱已经存在");
            return map;
        }

        String salt = CommunityUtils.getUUID().substring(0, 5);
        user.setSalt(salt);
        user.setPassword(CommunityUtils.md5(user.getPassword() + salt));
        user.setActivationCode(CommunityUtils.getUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        user.setType(0); //普通用户
        user.setStatus(0); //未激活

        userMapper.insertUser(user);

        //发送激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        //userId由Mybatis自增得到
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);

        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(), "牛客网激活邮件", content);

        return map;
    }

    @Override
    public Integer activate(int userId, String code) {
        User user = this.findUserById(userId);
        if (user == null) {
            return ACTIVATE_FAILURE;
        }
        if (user.getStatus() == 1) {
            //已经激活
            return ACTIVATE_REPEATED;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            clearCache(userId);
            return ACTIVATE_SUCCESS;
        } else {
            return ACTIVATE_FAILURE;
        }
    }

    @Override
    public int updateHeader(String head, int userId) {
//        return userMapper.updateHeader(userId,head);
        int result = userMapper.updateHeader(userId,head);
        clearCache(userId);//先更新再删除,防止更新失败却删除了。
        return result;
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.selectByName(username);
    }

    @Autowired
    RedisTemplate redisTemplate;

    private User getCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    private User initCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        User user = userMapper.selectById(userId);
        redisTemplate.opsForValue().set(userKey,user, 3600, TimeUnit.SECONDS);
        return user;
    }

    //任何更新的地方都需要清理缓存。
    private void clearCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

//    //返回当前用户的权限名
//    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
//        User user = userMapper.selectById(userId);
//        List<GrantedAuthority> list = new ArrayList<>();
//        list.add(new GrantedAuthority() {
//            @Override
//            public String getAuthority() {
//                switch (user.getType()) {
//                    case 1:
//                        return AUTHORITY_ADMIN;
//                    case 2:
//                        return AUTHORITY_MODERATOR;
//                    default:
//                        return AUTHORITY_USER;
//                }
//            }
//        });
//        return list;
//    }

    
}
